package gitee.wakyde.remoting.transport.netty.codec;

import gitee.wakyde.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;

/**
 * 自定义编码器
 */
@AllArgsConstructor
public class NettyKryoEncoder extends MessageToByteEncoder {
    private final Serialize serialize;
    private final Class<?> genericClass;

    /**
     * 将对象转换为字节码然后写入到ByteBuf对象中
     * @param channelHandlerContext
     * @param o
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if(genericClass.isInstance(o)){
            // 将对象转换为byte
            byte[] body = this.serialize.serialize(o);
            // 读取消息的长度
            int length = body.length;
            // 写入消息对应的字节数组长度，writerIndex加4
            byteBuf.writeByte(length);
            // 将字节数组写入ByteBuf对象中
            byteBuf.writeBytes(body);
        }
    }
}
